import json
import os
import uuid
from datetime import datetime

import pytz
from flask import Flask, Blueprint, Response, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.common.commonMessage import CommonMassages
from app.config.db import DBUtils
from app.config.jsonEncoder import CustomJSONEncoder
from app.model.RiskHistoryModel import RiskHistory
from app.model.RiskHistoryTempModel import RiskHistoryTemp
from app.service.RiskHistoryService import RiskHistoryService
from app.utils.ExcelManageUtils import ExcelManageUtils
from app.utils.XlsToXlsxUtils import XlsToXlsxUtils

app = Flask(__name__)
# 创建蓝图
risk_history_bp = Blueprint('risk_history_controller', __name__ , url_prefix='/kshx')

riskHistoryService = RiskHistoryService()

# 获取session
db_utils = DBUtils()
session = db_utils.get_session()

# 临时文件路径
file_path = '../static/tmpexcel/'
output_dir = '../static/tmpexcel/'

@risk_history_bp.route("/findall", methods=['GET'])
@jwt_required()
def findall():
    pageNum = int(request.args.get('pageNum'))
    pageSize = int(request.args.get('pageSize'))
    data = riskHistoryService.select_all_data(session, pageNum, pageSize)
    if data:
        respResult = {
            "code": 200,
            "data": data,
            "message": CommonMassages.CCD_SELECT_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False, default=str)
    return Response(resp_data, content_type='application/json')

@risk_history_bp.route("/findtplall", methods=['GET'])
@jwt_required()
def findtplall():
    pageNum = int(request.args.get('pageNum'))
    pageSize = int(request.args.get('pageSize'))
    data = riskHistoryService.select_all_temp_data(session, pageNum, pageSize)
    if data:
        respResult = {
            "code": 200,
            "data": data,
            "message": CommonMassages.CCD_SELECT_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False, default=str)
    return Response(resp_data, content_type='application/json')

@risk_history_bp.route("/blurfind", methods=['GET'])
@jwt_required()
def blurfind():
    pageNum = int(request.args.get('pageNum'))
    pageSize = int(request.args.get('pageSize'))
    company = None if request.args.get('company') in [None, '', 'null', 'None', 'undefined'] else request.args.get('company').strip()
    jylx = None if request.args.get('jylx') in [None, '', 'null', 'None', 'undefined'] else request.args.get('jylx').strip()
    data = riskHistoryService.select_data_by_condition(session, company, jylx, pageNum, pageSize)
    if data:
        respResult = {
            "code": 200,
            "data": data,
            "message": CommonMassages.CCD_SELECT_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False, default=str)
    return Response(resp_data, content_type='application/json')

@risk_history_bp.route("/timeintervaldata", methods=['GET'])
@jwt_required()
def timeintervaldata():
    pageNum = int(request.args.get('pageNum'))
    pageSize = int(request.args.get('pageSize'))
    type = request.args.get('type')
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    data = riskHistoryService.select_data_by_timeinterval(session, pageNum, pageSize, type, start_time, end_time)
    if data:
        respResult = {
            "code": 200,
            "data": data,
            "message": CommonMassages.CCD_SELECT_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False, default=str)
    return Response(resp_data, content_type='application/json')

@risk_history_bp.route("/timeintervaltpldata", methods=['GET'])
@jwt_required()
def timeintervaltpldata():
    pageNum = int(request.args.get('pageNum'))
    pageSize = int(request.args.get('pageSize'))
    type = request.args.get('type')
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    data = riskHistoryService.select_tpl_data_by_timeinterval(session, pageNum, pageSize, type, start_time, end_time)
    if data:
        respResult = {
            "code": 200,
            "data": data,
            "message": CommonMassages.CCD_SELECT_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_SELECT_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False, default=str)
    return Response(resp_data, content_type='application/json')

@risk_history_bp.route("/uploaddata", methods=['POST'])
@jwt_required()
def uploaddata():
    # 检查请求中是否包含文件
    if 'file' in request.files:
        file = request.files['file']
        # 检查是否是Excel文件
        if file and file.filename.endswith(('.xlsx', '.xls')):
            try:
                if file.filename.endswith('.xls'):
                    # 先将xls格式文件复制一份重命名存入临时处理文件夹tmp中
                    filename = f'{uuid.uuid4().hex}.xls'
                    excel_path = os.path.join(file_path, filename)
                    file.save(excel_path)
                    # 调用工具类将xls转为xlsx并将其保存到项目目录tmp下
                    xlsx_path = XlsToXlsxUtils.convert_file_to_xlsx(excel_path, output_dir)
                    # 获取工作表数据
                    result = ExcelManageUtils.get_excel_data(xlsx_path)
                    # 清除临时处理文件夹中生成的xlsx文件
                    if os.path.isfile(xlsx_path):
                        os.remove(xlsx_path)
                else:
                    # 获取工作表数据
                    result = ExcelManageUtils.get_excel_data(file)
                user_data = get_jwt_identity()
                pch = datetime.now(pytz.timezone('Asia/Shanghai')).strftime('%Y%m%d%H%M%S')
                creator = user_data['username']
                create_time = datetime.now(pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
                for item in result:
                    riskHistory = RiskHistory()
                    maxid = riskHistoryService.select_max_id(session)
                    riskHistory.ID = maxid + 1
                    riskHistory.CODE = item.get("编号")
                    riskHistory.FXBGPC = item.get("分析报告批次")
                    riskHistory.TGSJ = item.get("提供时间")
                    riskHistory.SSEJ = item.get("所属二级")
                    riskHistory.CYDW = item.get("成员单位")
                    riskHistory.JYDS = item.get("交易对手")
                    riskHistory.SXLX = item.get("涉险类型")
                    riskHistory.JYLX = item.get("交易类型")
                    riskHistory.JYBS = item.get("交易笔数")
                    riskHistory.JYJE = item.get("交易金额（万元）")
                    riskHistory.FKQK = item.get("反馈情况")
                    riskHistory.MZQK = item.get("命中情况")
                    riskHistory.PCH = pch
                    riskHistory.CREATOR = creator
                    riskHistory.CREATE_TIME = create_time
                    riskHistoryService.insert_data(session, riskHistory)
                respResult = {
                    "code": 200,
                    "data": None,
                    "message": CommonMassages.EXCEL_UPLOAD_SUCCESS.value
                }
            except Exception as e:
                print(e)
                respResult = {
                    "code": 400,
                    "data": None,
                    "message": CommonMassages.EXCEL_UPLOAD_FAILED.value
                }
        else:
            respResult = {
                "code": 400,
                "data": None,
                "message": CommonMassages.EXCEL_TYPE_ERROR.value
            }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.EXCEL_UPLOAD_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False)
    return Response(resp_data, content_type='application/json')

@risk_history_bp.route("/uploadtpldata", methods=['POST'])
@jwt_required()
def uploadtpldata():
    # 检查请求中是否包含文件
    if 'file' in request.files:
        file = request.files['file']
        # 检查是否是Excel文件
        if file and file.filename.endswith(('.xlsx', '.xls')):
            try:
                if file.filename.endswith('.xls'):
                    # 先将xls格式文件复制一份重命名存入临时处理文件夹tmp中
                    filename = f'{uuid.uuid4().hex}.xls'
                    excel_path = os.path.join(file_path, filename)
                    file.save(excel_path)
                    # 调用工具类将xls转为xlsx并将其保存到项目目录tmp下
                    xlsx_path = XlsToXlsxUtils.convert_file_to_xlsx(excel_path, output_dir)
                    # 获取工作表数据
                    result = ExcelManageUtils.get_excel_data(xlsx_path)
                    # 清除临时处理文件夹中生成的xlsx文件
                    if os.path.isfile(xlsx_path):
                        os.remove(xlsx_path)
                else:
                    # 获取工作表数据
                    result = ExcelManageUtils.get_excel_data(file)
                user_data = get_jwt_identity()
                pch = datetime.now(pytz.timezone('Asia/Shanghai')).strftime('%Y%m%d%H%M%S')
                creator = user_data['username']
                create_time = datetime.now(pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
                for item in result:
                    riskHistoryTemp = RiskHistoryTemp()
                    maxid = riskHistoryService.select_tpl_max_id(session)
                    riskHistoryTemp.ID = maxid + 1
                    riskHistoryTemp.CODE = item.get("编号")
                    riskHistoryTemp.FXBGPC = item.get("分析报告批次")
                    riskHistoryTemp.TGSJ = item.get("提供时间")
                    riskHistoryTemp.SSEJ = item.get("所属二级")
                    riskHistoryTemp.CYDW = item.get("成员单位")
                    riskHistoryTemp.JYDS = item.get("交易对手")
                    riskHistoryTemp.SXLX = item.get("涉险类型")
                    riskHistoryTemp.JYLX = item.get("交易类型")
                    riskHistoryTemp.JYBS = item.get("交易笔数")
                    riskHistoryTemp.JYJE = item.get("交易金额（万元）")
                    riskHistoryTemp.FKQK = item.get("反馈情况")
                    riskHistoryTemp.MZQK = item.get("命中情况")
                    riskHistoryTemp.PCH = pch
                    riskHistoryTemp.CREATOR = creator
                    riskHistoryTemp.CREATE_TIME = create_time
                    riskHistoryService.insert_temp_data(session, riskHistoryTemp)
                respResult = {
                    "code": 200,
                    "data": None,
                    "message": CommonMassages.EXCEL_UPLOAD_SUCCESS.value
                }
            except Exception as e:
                print(e)
                respResult = {
                    "code": 400,
                    "data": None,
                    "message": CommonMassages.EXCEL_UPLOAD_FAILED.value
                }
        else:
            respResult = {
                "code": 400,
                "data": None,
                "message": CommonMassages.EXCEL_TYPE_ERROR.value
            }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.EXCEL_UPLOAD_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False)
    return Response(resp_data, content_type='application/json')

@risk_history_bp.route("/clear", methods=['DELETE'])
@jwt_required()
def clear():
    result = riskHistoryService.clear_data(session)
    if result > 0:
        respResult = {
            "code": 200,
            "data": None,
            "message": CommonMassages.CCD_DELETE_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_DELETE_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False)
    return Response(resp_data, content_type='application/json')

@risk_history_bp.route("/delall", methods=['DELETE'])
@jwt_required()
def delall():
    req_data = request.get_json()
    json_data = json.loads(str(json.dumps(req_data)).replace("'", "\""))
    result = riskHistoryService.delete_all_data(session, json_data.get('ids'))
    if result > 0:
        respResult = {
            "code": 200,
            "data": None,
            "message": CommonMassages.CCD_DELETE_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_DELETE_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False)
    return Response(resp_data, content_type='application/json')

@risk_history_bp.route("/deltplall", methods=['DELETE'])
@jwt_required()
def deltplall():
    req_data = request.get_json()
    json_data = json.loads(str(json.dumps(req_data)).replace("'", "\""))
    result = riskHistoryService.delete_all_temp_data(session, json_data.get('ids'))
    if result > 0:
        respResult = {
            "code": 200,
            "data": None,
            "message": CommonMassages.CCD_DELETE_SUCCESS.value
        }
    else:
        respResult = {
            "code": 400,
            "data": None,
            "message": CommonMassages.CCD_DELETE_FAILED.value
        }
    resp_data = json.dumps(respResult, ensure_ascii=False)
    return Response(resp_data, content_type='application/json')

